package com.zyark.web.controller;


import com.zyark.domain.ArticleManage;
import com.zyark.service.ArticleManageService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@RequestMapping("api/v1/anon/article")
@Controller
public class ClientArticleController {


    @Resource
    ArticleManageService articleManageService;

    @RequestMapping(value = "list",method = RequestMethod.GET)
    @ResponseBody
    public Object getList(@RequestParam(value = "pageNum",required = false)Integer pageNumber,@RequestParam(value = "pageSize",required = false)Integer pageSize){
        if (pageNumber == null){
            pageNumber = 1;
        }
        if (pageSize == null){
            pageSize = 5;
        }
        return articleManageService.selectPageV2(pageNumber,pageSize);
    }


    /**
     * 获取文章详情
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    @ResponseBody
    public Object getArticle(@PathVariable Integer id){
        Map<String,Object> result = new HashMap<>();
        ArticleManage news = articleManageService.selectByPrimary(new ArticleManage(id));
        //阅读量加1
        Integer viewNumber = news.getViewNumber() + 1;
        news.setViewNumber(viewNumber);
        articleManageService.updateSelective(news);

        Integer priority = Integer.valueOf(news.getPriority());
        ArticleManage findPreNews = new ArticleManage();
        findPreNews.setPriority(String.valueOf(priority-1));
        ArticleManage preNews = articleManageService.selectOne(findPreNews);

        ArticleManage findNextNews = new ArticleManage();
        findNextNews.setPriority(String.valueOf(priority+1));
        ArticleManage nextNews = articleManageService.selectOne(findNextNews);

        result.put("news",news);
        Example example = new Example(ArticleManage.class);
        Set<Integer> selfId = new HashSet<>();
        selfId.add(id);
        example.or().andLessThanOrEqualTo("createTime",news.getCreateTime()).andNotIn("id",selfId);
        result.put("newsRelative",articleManageService.selectPageByExample(example,1,5));
        result.put("pre",preNews);
        result.put("next",nextNews);
        return result;
    }
}
